<template>
  <div class="v-org-mgt">
    <c-row-crumb :title="multLang('title_aaaav')">
      <c-select-more
        class="v-org-add"
        v-show="!visibles.group.add && !visibles.position.add"
        @command="moreActions"
      >
        <el-button type="primary">
          {{ multLang('btn_new_a') }}
          <c-icon name="down"></c-icon>
        </el-button>

        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item command="addGroup">
            {{ tplLang('btn_wsq_a', ['title_ba_m']) }}
          </el-dropdown-item>
          <el-dropdown-item command="addPosition">
            {{ tplLang('btn_wsq_a', ['title_pf']) }}
          </el-dropdown-item>
        </el-dropdown-menu>
      </c-select-more>

      <el-button v-show="visibles.group.add" @click="cancelSubmit">
        {{ multLang('btn_cancel_a') }}
      </el-button>
      <el-button
        v-show="visibles.group.add"
        type="primary"
        @click="submitGroup"
      >
        {{ multLang('btn_save_a') }}
      </el-button>

      <el-button v-show="visibles.position.add" @click="cancelSubmit">
        {{ multLang('btn_cancel_a') }}
      </el-button>
      <el-button
        v-show="visibles.position.add"
        type="primary"
        @click="submitPosition"
      >
        {{ multLang('btn_save_a') }}
      </el-button>
      <el-button
        v-show="!visibles.group.add && !visibles.position.add"
        @click="del"
        >{{ multLang('btn_delete_a') }}</el-button
      >
    </c-row-crumb>
    <c-row less-width="20px" class="v-org-bot">
      <c-col :col="3" top>
        <div class="v-org-title">
          {{ multLang('title_ba_m', ' - ', 'title_pf') }}
        </div>
        <c-roll class="v-org-menu">
          <el-tree
            ref="tree"
            :data="tree.data"
            node-key="value"
            @node-click="confirm"
            default-expand-all
            highlight-current
            :expand-on-click-node="false"
          >
            <template slot-scope="{ data }">
              <c-text-long>
                {{
                  data.label + (data.out ? '(' + multLang('text_bc') + ')' : '')
                }}
              </c-text-long>
            </template>
          </el-tree>
        </c-roll>
      </c-col>
      <c-col less></c-col>
      <c-col :col="9" top>
        <c-row-view
          :title="tplLang('tab_device_c', ['title_ba_m'])"
          v-show="tree.info.is_group && !visibles.group.add"
        >
          <template #opn>
            <c-row-view-opn
              :auth="true"
              :visible.sync="visibles.group.edit"
              @cancel="cancelGroup"
              @save="saveGroup"
              @edit-click="editClickGroup"
            >
            </c-row-view-opn>
          </template>
          <el-form
            :model="form.group.edit"
            :rules="groupRules"
            ref="groupEditForm"
            label-width="140px"
            :validate-on-rule-change="false"
          >
            <c-row :col="4">
              <c-col>
                <el-form-item
                  :label="multLang('title_ba_m', 'title_name_ab_b', ':')"
                  prop="group_name"
                >
                  <c-form-edit :visible="visibles.group.edit">
                    <template #edit>
                      <el-input
                        v-model="form.group.edit.group_name"
                        :placeholder="multLang('text_d')"
                      ></el-input>
                    </template>
                    <c-text-long>
                      {{ tree.info.group_name }}
                    </c-text-long>
                  </c-form-edit>
                </el-form-item>
              </c-col>
              <c-col>
                <el-form-item
                  :label="multLang('text_au', ':')"
                  prop="parent_id"
                >
                  <c-form-edit :visible="visibles.group.edit">
                    <template #edit>
                      <c-cascader
                        show-all-levels
                        v-model="form.group.edit.parent_id"
                        :options="list.editGroup"
                        clearable
                        :placeholder="multLang('title_aaad_h')"
                      ></c-cascader>
                    </template>
                    <c-text-long>
                      {{
                        list.groupMap[tree.info.parent_id] ||
                          multLang('title_aaad_h')
                      }}
                    </c-text-long>
                  </c-form-edit>
                </el-form-item>
              </c-col>

              <c-col :col="11">
                <el-form-item
                  :label="multLang('title_ba_m', 'title_aah_h', ':')"
                  prop="remark"
                >
                  <c-form-edit :visible="visibles.group.edit" long>
                    <template #edit>
                      <c-input-text
                        v-model="form.group.edit.remark"
                      ></c-input-text>
                    </template>
                    <span>{{ tree.info.remark }}</span>
                  </c-form-edit>
                </el-form-item>
              </c-col>
              <c-col>
                <el-form-item :label="multLang('title_aau_j', 'text_av', ':')">
                  <c-form-edit :visible="visibles.group.edit">
                    <template #edit>
                      <span>
                        {{
                          tree.info.is_out
                            ? multLang('text_aw')
                            : multLang('text_av')
                        }}
                      </span>
                    </template>
                    <span>
                      {{
                        tree.info.is_out
                          ? multLang('text_aw')
                          : multLang('text_av')
                      }}
                    </span>
                  </c-form-edit>
                </el-form-item>
              </c-col>
              <c-col v-show="tree.info.is_out">
                <el-form-item :label="multLang('title_b_o', ':')">
                  <c-form-edit :visible="visibles.group.edit">
                    <template #edit>
                      <!-- <c-cascader
                        show-all-levels
                        v-model="form.group.edit.select_facilities"
                        :options="[]"
                        :placeholder="multLang('please_choose')"
                      >
                      </c-cascader> -->
                      <span>{{ tree.info.title }}</span>
                    </template>
                    <span>{{ tree.info.title }}</span>
                  </c-form-edit>
                </el-form-item>
              </c-col>
            </c-row>
          </el-form>
        </c-row-view>
        <c-row-add
          v-show="visibles.group.add"
          :title="multLang('btn_new_a', 'title_ba_m')"
        >
          <el-form
            :model="form.group.add"
            :rules="groupRules"
            ref="groupForm"
            label-width="140px"
            :validate-on-rule-change="false"
          >
            <c-row :col="6">
              <c-col>
                <el-form-item
                  :label="multLang('title_ba_m', 'title_name_ab_b', ':')"
                  prop="group_name"
                >
                  <el-input
                    v-model="form.group.add.group_name"
                    :placeholder="multLang('text_d')"
                  ></el-input>
                </el-form-item>
              </c-col>
              <c-col>
                <el-form-item
                  :label="multLang('text_au', ':')"
                  prop="parent_id"
                >
                  <c-cascader
                    v-model="form.group.add.parent_id"
                    show-all-levels
                    :options="list.group"
                    clearable
                    :placeholder="multLang('title_aaad_h')"
                    @change="addGoroupChange"
                  ></c-cascader>
                </el-form-item>
              </c-col>

              <c-col :col="11">
                <el-form-item
                  :label="multLang('title_ba_m', 'title_aah_h', ':')"
                  prop="remark"
                >
                  <c-input-text v-model="form.group.add.remark"></c-input-text>
                </el-form-item>
              </c-col>
              <c-col>
                <el-form-item
                  :label="multLang('text_bc', '/', 'text_av', ':')"
                  prop="is_out"
                >
                  <el-radio-group
                    v-model="form.group.add.is_out"
                    @change="isOutChange"
                    :disabled="!!form.group.add.parent_id"
                  >
                    <el-radio :label="false">
                      {{ multLang('text_av') }}
                    </el-radio>
                    <el-radio :label="true">{{ multLang('text_aw') }}</el-radio>
                  </el-radio-group>
                </el-form-item>
              </c-col>
              <c-col v-show="form.group.add.is_out">
                <el-form-item
                  :label="multLang('title_dn', 'title_b_o', ':')"
                  prop="org_id"
                >
                  <c-cascader
                    :disabled="!!form.group.add.parent_id"
                    show-all-levels
                    v-model="form.group.add.org_id"
                    :options="customerFacilitiesList"
                    clearable
                    :placeholder="tplLang('text_choose_a', ['title_b_o'])"
                  >
                  </c-cascader>
                </el-form-item>
              </c-col>
            </c-row>
          </el-form>
        </c-row-add>
        <c-row-view
          :title="tplLang('tab_device_c', ['title_pf'])"
          v-show="tree.info.is_position && !visibles.position.add"
        >
          <template #opn>
            <c-row-view-opn
              :auth="true"
              :visible.sync="visibles.position.edit"
              @cancel="cancelPosition"
              @save="savePosition"
            >
            </c-row-view-opn>
          </template>
          <el-form
            :model="form.position.edit"
            :rules="positionRules"
            ref="positionEditForm"
            label-width="140px"
            :validate-on-rule-change="false"
          >
            <c-row :col="6">
              <c-col>
                <el-form-item :label="multLang('text_ax', ':')" prop="group_id">
                  <c-form-edit :visible="visibles.position.edit">
                    <template #edit>
                      <c-cascader
                        show-all-levels
                        v-model="form.position.edit.group_id"
                        :options="list.group"
                        clearable
                        :placeholder="tplLang('text_choose_a', ['title_ba_m'])"
                      ></c-cascader>
                    </template>
                    <c-text-long>
                      {{ list.groupMap[tree.info.group_id] }}
                    </c-text-long>
                  </c-form-edit>
                </el-form-item>
              </c-col>
              <c-col>
                <el-form-item
                  :label="multLang('title_pf', 'title_name_ab_b', ':')"
                  prop="position_name"
                >
                  <c-form-edit :visible="visibles.position.edit">
                    <template #edit>
                      <el-input
                        v-model="form.position.edit.position_name"
                        :placeholder="tplLang('text_choose_a', ['title_ba_m'])"
                      ></el-input>
                    </template>
                    <c-text-long>{{ tree.info.position_name }}</c-text-long>
                  </c-form-edit>
                </el-form-item>
              </c-col>

              <c-col :col="11">
                <el-form-item
                  :label="multLang('title_pf', 'title_aah_h', ':')"
                  prop="remark"
                >
                  <c-form-edit :visible="visibles.position.edit" long>
                    <template #edit>
                      <c-input-text
                        v-model="form.position.edit.remark"
                      ></c-input-text>
                    </template>
                    <span>{{ tree.info.remark }}</span>
                  </c-form-edit>
                </el-form-item>
              </c-col>
            </c-row>
          </el-form>
        </c-row-view>
        <c-row-add
          :title="multLang('btn_new_a', 'title_pf')"
          v-show="visibles.position.add"
        >
          <el-form
            :model="form.position.add"
            :rules="positionRules"
            ref="positionForm"
            label-width="140px"
            :validate-on-rule-change="false"
          >
            <c-row :col="6">
              <c-col>
                <el-form-item :label="multLang('text_ax', ':')" prop="group_id">
                  <c-cascader
                    show-all-levels
                    v-model="form.position.add.group_id"
                    :options="list.group"
                    clearable
                    :placeholder="tplLang('text_choose_a', ['title_ba_m'])"
                  ></c-cascader>
                </el-form-item>
              </c-col>
              <c-col>
                <el-form-item
                  :label="multLang('title_pf', 'title_name_ab_b', ':')"
                  prop="position_name"
                >
                  <el-input
                    v-model="form.position.add.position_name"
                    :placeholder="multLang('text_d')"
                  ></el-input>
                </el-form-item>
              </c-col>
              <c-col :col="11">
                <el-form-item
                  :label="multLang('title_pf', 'title_aah_h', ':')"
                  prop="remark"
                >
                  <c-input-text
                    v-model="form.position.add.remark"
                  ></c-input-text>
                </el-form-item>
              </c-col>
            </c-row>
          </el-form>
        </c-row-add>

        <c-row-add
          :title="multLang('title_dn', 'title_am_y')"
          v-if="tree.info.is_position"
          class="v-org-role"
        >
          <template #right>
            <c-position-role-add
              :data="tree.click"
              @close="query"
            ></c-position-role-add>
          </template>
          <div class="v-org-role-table">
            <c-table :data="table.data" :col="table.col">
              <template #opn="{ row }">
                <el-button type="text" @click="delRole(row)">
                  <c-icon name="delete"></c-icon>
                  <span>
                    {{ multLang('btn_delete_a') }}
                  </span>
                </el-button>
              </template>
              <!-- <template #opn>
                <el-table-column width="200px" fixed="right" align="center">
                  <template slot="header" slot-scope="{}">
                    {{ multLang('title_action_a') }}
                  </template>
                  <div slot-scope="{ row }" style="text-align: center">
                    <el-button type="text" @click="delRole(row)">
                      <c-icon name="delete"></c-icon>
                      <span>
                        {{ multLang('btn_delete_a') }}
                      </span>
                    </el-button>
                  </div>
                </el-table-column>
              </template> -->
            </c-table>
          </div>
        </c-row-add>
      </c-col>
    </c-row>
  </div>
</template>
<script>
import {
  addGroupData,
  addPositionData,
  delGroupData,
  delPositionData,
  delPositionRoleData,
  editGroupData,
  editPositionData,
  getGroupData,
  getGroupInfo,
  getGroupOption,
  getPositionInfo,
  getPositionRoleInfo
} from '@/http/api/v1/org'
import { ObjectCopy } from '@/util'
import CPositionRoleAdd from './mod/PositionRoleAdd.vue'

export default {
  name: 'VOrgMgt',
  components: { CPositionRoleAdd },
  props: {},
  data() {
    return {
      visibles: {
        group: {
          add: false,
          edit: false
        },
        position: {
          add: false,
          edit: false
        }
      },
      list: {
        editGroup: [],
        group: [],
        groupMap: {}
      },
      form: {
        group: {
          add: {
            group_name: '',
            parent_id: '',
            remark: '',
            is_out: false,
            org_id: ''
          },
          edit: {
            group_name: '',
            parent_id: '',
            remark: '',
            is_out: false,
            org_id: '',
            title: ''
          }
        },
        position: {
          add: {
            group_id: '',
            position_name: '',
            remark: ''
          },
          edit: {
            group_id: '',
            position_name: '',
            remark: ''
          }
        }
      },
      tree: {
        info: {},
        click: {},
        data: []
      },
      table: {
        data: [],
        col: [
          { label: 'title_name_w', prop: 'name' },
          { label: 'text_bd', prop: 'description' }
        ]
      }
    }
  },
  computed: {
    customerFacilitiesList() {
      return this.optionList('customerFacilities')
    },
    groupRules() {
      const rule = {
        group_name: {
          required: true,
          message: this.multLang('msg_g'),
          trigger: 'blur'
        }
      }
      this.form.group.add.is_out &&
        (rule.org_id = {
          required: true,
          message: this.tplLang('text_choose_a'),
          trigger: 'change'
        })
      return rule
    },
    positionRules() {
      return {
        group_id: {
          required: true,
          message: this.multLang('msg_g'),
          trigger: 'change'
        },
        position_name: {
          required: true,
          message: this.tplLang('text_choose_a'),
          trigger: 'blur'
        }
      }
    }
  },
  watch: {},
  beforeCreate() {},
  created() {
    this.setOption({ key: 'customerFacilities' })
    this.query()
    this.getGroupOption()
  },
  beforeMount() {},
  mounted() {},
  beforeUpdate() {},
  updated() {},
  activated() {
    this.query()
  },
  deactivated() {},
  beforeDestroy() {},
  destroyed() {},
  methods: {
    getGroupOption() {
      getGroupOption().then(({ data, map }) => {
        this.list.group = data
        this.list.groupMap = map
      })
    },
    query() {
      getGroupData().then(({ data = [] }) => {
        this.tree.data = data
        const nid = this.tree.click.id || (data[0] && data[0].id)
        nid &&
          this.$nextTick().then(() => {
            this.$refs.tree.setCurrentKey(nid)
            this.treeClick(this.$refs.tree.getCurrentNode())
          })
      })
    },
    addGoroupChange(_, data) {
      const { out, org_id } = data || {}
      this.form.group.add.is_out = out || false
      this.form.group.add.org_id = org_id || ''
    },
    isOutChange(val) {
      val || (this.form.group.add.org_id = '')
    },

    moreActions(cmd) {
      const fn = this[cmd]
      fn && typeof fn === 'function' && fn()
    },
    addGroup() {
      this.tree.info = {}
      this.visibles.position.add = false
      this.visibles.group.add = true
      // this.getGroupOption()
    },
    addPosition() {
      this.tree.info = {}
      this.visibles.group.add = false
      this.visibles.position.add = true
      // this.getGroupOption()
    },
    del() {
      this.$confirm(
        this.tplLang('text_ah', ['btn_delete_a', 'title_ba_m']),
        this.multLang('btn_delete_a', 'title_ba_m'),
        {
          confirmButtonText: this.multLang('btn_sure_a'),
          cancelButtonText: this.multLang('btn_cancel_a'),
          type: 'warning',
          iconClass: 'c-icon icon-info-circle color-danger'
        }
      ).then(() => {
        const { id, group } = this.tree.click
        if (group) {
          id &&
            delGroupData({ group_id: id }).then(({ code }) => {
              if (code === 200) {
                this.tree.click = {}
                this.query()
              }
            })
        } else {
          id &&
            delPositionData({ position_id: id }).then(({ code }) => {
              if (code === 200) {
                this.tree.click = {}
                this.query()
              }
            })
        }
      })
    },
    delRole(row = {}) {
      this.$confirm(
        this.tplLang('text_ah', ['btn_delete_a', 'title_am_y']),
        this.multLang('btn_delete_a', 'title_am_y'),
        {
          confirmButtonText: this.multLang('btn_sure_a'),
          cancelButtonText: this.multLang('btn_cancel_a'),
          type: 'warning',
          iconClass: 'c-icon icon-info-circle color-danger'
        }
      ).then(() => {
        const { id: position_id } = this.tree.click
        const { id: roleId } = row
        position_id &&
          roleId &&
          delPositionRoleData({ position_id, roleId }).then(() => {
            this.query()
          })
      })
    },
    submitGroup() {
      this.$refs.groupForm.validate(valid => {
        if (valid) {
          addGroupData({
            ...this.form.group.add
          }).then(({ code }) => {
            if (code === 200) {
              this.query()
              this.getGroupOption()
            }
          })
        }
      })
    },
    submitPosition() {
      this.$refs.positionForm.validate(valid => {
        if (valid) {
          addPositionData({
            ...this.form.position.add
          }).then(({ code }) => {
            code === 200 && this.query()
          })
        }
      })
    },
    cancelSubmit() {
      this.visibles.group.add = false
      this.visibles.position.add = false

      this.treeClick(this.$refs.tree.getCurrentNode())
    },
    cancelGroup() {
      this.visibles.group.edit = false
      this.$nextTick().then(() => this.$refs.groupEditForm.clearValidate())
    },
    cancelPosition() {
      this.visibles.position.edit = false
      this.$nextTick().then(() => this.$refs.positionEditForm.clearValidate())
    },
    saveGroup() {
      this.$refs.groupEditForm.validate(valid => {
        if (valid) {
          const { id } = this.tree.info
          editGroupData({ group_id: id, ...this.form.group.edit }).then(() => {
            this.visibles.group.edit = false
            this.query()
            this.getGroupOption()
          })
        }
      })
    },
    savePosition() {
      this.$refs.positionEditForm.validate(valid => {
        if (valid) {
          const { id } = this.tree.info
          editPositionData({
            position_id: id,
            ...this.form.position.edit
          }).then(() => {
            this.visibles.position.edit = false
            this.query()
          })
        }
      })
    },
    confirm(node = {}) {
      if (this.visibles.group.add || this.visibles.position.add) {
        this.$confirm(
          this.multLang('title_aau_j', 'btn_save_a', '?'),
          this.multLang('title_aaz_d'),
          {
            confirmButtonText: this.multLang('btn_sure_a'),
            cancelButtonText: this.multLang('btn_cancel_a'),
            type: 'warning',
            iconClass: 'c-icon icon-info-circle color-danger'
          }
        )
          .then(() => {
            if (this.visibles.group.add) {
              this.submitGroup()
            }
            if (this.visibles.position.add) {
              this.submitPosition()
            }
          })
          .catch(() => {
            this.treeClick(node)
          })
      } else {
        this.treeClick(node)
      }
    },
    treeClick(node = {}) {
      this.tree.click = node
      this.visibles.group.add = false
      this.visibles.position.add = false
      const { id, gname, pname } = node
      if (id && (gname || pname)) {
        gname &&
          getGroupInfo({ group_id: id }).then(({ data }) => {
            const info = { ...data, is_group: true }
            this.tree.info = info
            ObjectCopy(this.form.group.edit, info)
          })
        if (pname) {
          getPositionInfo({ position_id: id }).then(({ data }) => {
            const info = { ...data, is_position: true }
            this.tree.info = info
            ObjectCopy(this.form.position.edit, info)
          })
          getPositionRoleInfo({ position_id: id }).then(({ data }) => {
            this.table.data = data || []
          })
        }
      }
    },
    editClickGroup() {
      const { id, is_out } = this.tree.info
      getGroupOption({ id, is_out }).then(({ data }) => {
        this.list.editGroup = data
      })
    }
  }
}
</script>
<style lang="scss">
.v-org {
  &-mgt {
  }
  &-add {
    // margin-right: 10px;
  }
  &-title {
    padding: 0 20px;
    height: 42px;
    line-height: 42px;
    font-size: 16px;
    color: #333;
    background-color: #fff;
    border-radius: 4px;
    margin-bottom: 10px;
  }
  &-bot {
    height: calc(100% - 42px);
  }
  &-menu {
    box-sizing: border-box;
    height: calc(100% - 52px);
    padding: 20px;
    background-color: #fff;
    .c-text-long {
      font-size: 14px;
    }
  }
  &-role {
    height: calc(100% - 168px);
    &-table {
      height: calc(100% - 80px);
      padding: 0 18px 18px 18px;
    }
  }
}
</style>
